package crontab

import (
	"encoding/json"
	"fmt"
	maasentity "github.com/maas/gomaasclient/entity"
	"github.com/maas/gomaasclient/entity/node"
	"github.com/robfig/cron/v3"
	config "gluenet/configs"
	"gluenet/internal/glue-srvm/pkg/gluelog"
	"gluenet/pkg/agent"
	corev1 "gluenet/pkg/agent/types"
	"gluenet/pkg/agent/v2/rpc"
)

func CronDeploy() {
	c := cron.New()
	spec := fmt.Sprintf("* * * * *")
	_, err := c.AddFunc(spec, func() {
		gluelog.Infoln("开始自动部署")
		Deploy()
	})
	if err != nil {
		gluelog.Errorln("部署失败", "err:", err)
	}
	c.Start()
	gluelog.Infoln("自动部署任务开始")
}

// Deploy Polling the node status until it is deployed
func Deploy() {
	agentGuid := config.GetConfig().MaasAgentName
	cli, err := agent.NewAgent(&rpc.Config{
		Target:  agentGuid,
		NatsUrl: config.GetConfig().NatsServerAddr,
	})
	if err != nil {
		gluelog.Errorf("rpc url is empty", err.Error())
		return
	}
	// 1.Search all machines
	var machines []maasentity.Machine
	rlt, err := cli.Maas().MachinesSearch(&corev1.MaasReq{MaasURL: config.GetConfig().MaasUrl, APIKey: config.GetConfig().MaasAPIKey, Version: config.GetConfig().MaasAPIVersion})
	if err != nil {
		gluelog.Errorf("failed to request rpc,unable to deploy machine", err.Error())
		return
	}
	_ = json.Unmarshal(rlt, &machines)
	// 2.Judge and deploy
	for _, machine := range machines {
		if machine.Status == node.StatusReady {
			massReq := corev1.MaasReq{
				MaasURL:   config.GetConfig().MaasUrl,
				APIKey:    config.GetConfig().MaasAPIKey,
				Version:   config.GetConfig().MaasAPIVersion,
				GetParams: machine.SystemID,
				Value:     map[string]string{},
			}
			_, err := cli.Maas().MachineDeploy(&massReq)
			if err != nil {
				gluelog.Errorf("failed to request rpc", err.Error())
				return
			} else {
				gluelog.Infof("deploy success, machine id is %s", machine.SystemID)
			}
		}
	}
}
